package com.steven.im.ui.fragment.goodsdetail;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.Paint;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.view.animation.ScaleAnimation;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.flyco.tablayout.SlidingTabLayout;
import com.steven.im.App;
import com.steven.im.R;
import com.steven.im.adapter.DetailsBisRecordAdapter;
import com.steven.im.base.ViewPagerFragment;
import com.steven.im.entity.BaseEntity;
import com.steven.im.entity.BaseEventEntity;
import com.steven.im.entity.BidRecordEntity;
import com.steven.im.imageLoader.GlideImageLoader;
import com.steven.im.net.MyCallback;
import com.steven.im.net.Task;
import com.steven.im.ui.activity.BidRecordActivity;
import com.steven.im.utils.FormattedDataUtils;
import com.steven.im.utils.SPUtils;
import com.steven.im.utils.SimpleCountDownTimer;
import com.steven.im.widget.DetailWebView;
import com.steven.im.widget.MyScrollView;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import retrofit2.Response;

/**
 * Created by Steven on 2019/1/15.
 */
@SuppressLint("ValidFragment")
public class GoodsFragment extends ViewPagerFragment {
    private RelativeLayout headerRel;
    private RelativeLayout titleBar;
    private RelativeLayout iconBar;
    private int currentY = 0;//当前滑动的Y轴距离
    private ImageView backImg;
    private ImageView shareImg;
    private ImageView backImg1;
    private ImageView shareImg1;
    private SlidingTabLayout slidingTabLayout;
    private View view;
    private boolean isFirst = true;//判断是不是第一次加载
    //所有信息展示的view
    private Banner banner;//商品显示轮播
    private TextView tv_nowMoney;//现在价格
    private TextView tv_oldMoney;//过去价格
    private LinearLayout ll_lastTime;//还剩时间
    private View v_line;//中间 线段
    private TextView tv_goodName;//商品名字
    private TextView tv_goodDetail;//商品描述
    private RelativeLayout rl_bid1;//出价记录
    private LinearLayout ll_bid2;//竞拍描述
    private DetailWebView webView;//商品详情
    private MyScrollView scrollView;//外层scrollView

    private JSONObject object;//获取jsonObject对象

    private TextView tv_lastTime;//还剩时间
    private TextView tv_openBid;//起拍价
    private TextView tv_openBidOne;//起拍价基数
    private TextView tv_addPrice;//加价幅度
    private TextView tv_bidLast;//竞拍倒计时
    private TextView tv_chajia;//差价购买
    private TextView tv_tuibi;//退币比例
    private TextView tv_more;//查看更多出价记录
    private LinearLayout ll_money;
    private List<BidRecordEntity> list;//竞价记录
    private TextView tv_bid_title;
    private DetailsBisRecordAdapter detailsBisRecordAdapter = null;
    private RecyclerView recyclerView;
    private SimpleCountDownTimer simpleCountDownTimer;//全局的倒计时

    public GoodsFragment(JSONObject bean, RelativeLayout headerRel, SlidingTabLayout slidingTabLayout, ImageView backImg, ImageView shareImg, ImageView backImg1, ImageView shareImg1) {
        this.object = bean;
        this.headerRel = headerRel;
        this.titleBar = headerRel.findViewById(R.id.rl_titlebar);
        this.iconBar = headerRel.findViewById(R.id.rl_iconbar);
        this.slidingTabLayout = slidingTabLayout;
        this.backImg = backImg;
        this.shareImg = shareImg;
        this.shareImg1 = shareImg1;
        this.backImg1 = backImg1;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_good, null);
        EventBus.getDefault().register(this);
        initView();
        setWebView();
        return view;
    }

    private void initView() {
        scrollView = view.findViewById(R.id.scrollView);
        banner = view.findViewById(R.id.banner);
        tv_nowMoney = view.findViewById(R.id.tv_nowMoney);
        tv_oldMoney = view.findViewById(R.id.tv_oldMoney);
        ll_lastTime = view.findViewById(R.id.ll_lastTime);
        v_line = view.findViewById(R.id.v_line);
        tv_goodName = view.findViewById(R.id.tv_goodName);
        tv_goodDetail = view.findViewById(R.id.tv_goodDetail);
        rl_bid1 = view.findViewById(R.id.rl_bid1);
        ll_bid2 = view.findViewById(R.id.ll_bid2);
        tv_lastTime = view.findViewById(R.id.tv_lastTime);
        tv_more = view.findViewById(R.id.tv_more);
        tv_openBid = view.findViewById(R.id.tv_openBid);
        tv_openBidOne = view.findViewById(R.id.tv_openBidOne);
        tv_addPrice = view.findViewById(R.id.tv_addPrice);
        tv_bidLast = view.findViewById(R.id.tv_bidLast);
        tv_chajia = view.findViewById(R.id.tv_chajia);
        tv_tuibi = view.findViewById(R.id.tv_tuibi);
        tv_bid_title = view.findViewById(R.id.tv_bid_title);
        ll_money = view.findViewById(R.id.ll_money);
        tv_more.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), BidRecordActivity.class).putExtra("issuedNo", object.getString("issuedNo")));
            }
        });
        (view.findViewById(R.id.vv_onclick)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(getActivity(), BidRecordActivity.class).putExtra("issuedNo", object.getString("issuedNo")));
            }
        });
        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setNestedScrollingEnabled(false);//禁止滑动
        recyclerView.setLayoutManager(linearLayoutManager);
        ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
    }

    /**
     * 第一次可见
     */
    @Override
    protected void onFirstUserVisible() {
        initData();
        //初始化标题栏状态
        headerRel.getBackground().setAlpha(0);//背景透明
        titleBar.setVisibility(View.GONE);//文字标题不可见
        iconBar.setVisibility(View.VISIBLE);//按钮标题可见
    }

    private void initData() {
        if (("1").equals(object.getString("salesType"))) {
            list = new ArrayList<>();//如果是竞拍商品 进行初始化
            setBidViewData(object);
        } else {
            //设置 普通商品  和 虚拟商品
            setViewData(object);
        }
    }


    /**
     * 其他可见
     */
    @Override
    protected void onUserVisible() {
//        getGoodDetail();
        //对用户可见时,根据Y轴位置显示状态栏
        setTitleBarStatus(currentY);

    }

    @Override
    protected void onUserInvisible() {
        //对用户不可见的时候
    }

    //获取商品信息
    private void getGoodDetail() {
        Task.getApiService().getGoodDetail(object.getString("issuedNo")).enqueue(new MyCallback<BaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<BaseEntity> response) {
                try {
                    if ("0".equals(response.body().getCode())) {
                        if (("1").equals(object.getString("salesType"))) {
                            setBidViewData(response.body().getResult());
                        } else {
                            //设置 普通商品  和 虚拟商品
                            setViewData(response.body().getResult());
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //初始化 banner信息
    private void initBanner(List<String> list) {
        //        //设置banner样式
        banner.setBannerStyle(BannerConfig.NUM_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(list);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
        //设置自动轮播，默认为true
        banner.isAutoPlay(false);
        //设置轮播时间
        banner.setDelayTime(5000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.LEFT);
        banner.start();
        banner.startAutoPlay();
    }

    //设置普通/虚拟商品信息
    @SuppressLint("SetTextI18n")
    private void setViewData(JSONObject object) {
        if (isFirst) {
            //获取  图片 链接
            List<String> url_list = new ArrayList<>();//存放图片的
            String[] url = object.getString("carouselImage").split(",");
            Collections.addAll(url_list, url);
            initBanner(url_list);//初始化  banner信息
            String originalPrice = object.getString("originalPrice");
            String[] str = (originalPrice.trim()).split("\\.");
            if (str.length == 2) {
                if (("0").equals(str[0]) && ("00").equals(str[1])) {
                    tv_oldMoney.setVisibility(View.INVISIBLE);
                } else {
                    tv_oldMoney.setVisibility(View.VISIBLE);
                }
            } else if (str.length == 0) {
                if (("0").equals(originalPrice)) {
                    tv_oldMoney.setVisibility(View.INVISIBLE);
                }
            }
            v_line.setVisibility(View.GONE);
            tv_nowMoney.setText(object.getString("discountPrice"));
            tv_oldMoney.setText("￥" + object.getString("originalPrice"));
            tv_oldMoney.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            tv_goodName.setText(object.getString("title"));
            tv_goodDetail.setText(object.getString("description"));
            String detail = object.getString("details");
            SPUtils.put(App.getContext(), "detail_url", detail);
            isFirst = false;
            webView.loadUrl(detail);
        }
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(BaseEventEntity baseEventEntity) {
        //获取出价记录  然后进行设置
        try {
            if ("detail".equals(baseEventEntity.getTitle())) {
                JSONObject object = baseEventEntity.getResult();
                if (object.containsKey("goods")) {
                    JSONObject myJsonObject = (JSONObject) (JSON.toJSON(object.get("goods")));
                    long time = 0;
                    if (myJsonObject.containsKey("biddingCountdown")) {
                        time = Long.parseLong(((JSONObject) (JSON.toJSON(object.get("goods")))).getString("biddingCountdown"));
                    }
                    simpleCountDownTimer.cancel();
                    simpleCountDownTimer = null;
                    simpleCountDownTimer = new SimpleCountDownTimer(time, tv_lastTime);
                    simpleCountDownTimer.start();
                    String money = myJsonObject.getString("biddingPrice");
                    if (!money.equals(tv_nowMoney.getText().toString())) {
                        tv_nowMoney.setText(money);
                        ScaleAnimation scaleAnimation = (ScaleAnimation) AnimationUtils.loadAnimation(App.getContext(), R.anim.zoom_scale);
                        ll_money.startAnimation(scaleAnimation);
                    }
                    tv_bid_title.setText("如无人出价，将以" + myJsonObject.getString("biddingPrice") + "价格获得该商品");
                }
                JSONArray array = object.getJSONArray("biddingRecodeList");  //获取出价记录
                if (array.size() == 0) {
                    rl_bid1.setVisibility(View.GONE);
                } else {
                    rl_bid1.setVisibility(View.VISIBLE);
                    setRecordList(array);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    //新设置竞价记录列表
    private void setRecordList(JSONArray array) {
        List<BidRecordEntity> myList = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            //遍历结果 设置出价记录
            if (i <= 2) {
                BidRecordEntity bidRecordEntity = new BidRecordEntity();
                JSONObject jsonObject = JSON.parseObject(array.getString(i));
                bidRecordEntity.setUrl(jsonObject.getString("userAvatar"));
                bidRecordEntity.setPhone(jsonObject.getString("userNickname"));
                bidRecordEntity.setStatus(jsonObject.getString("biddingStatus"));
                bidRecordEntity.setAddress(jsonObject.getString("userCity"));
                bidRecordEntity.setMoney("￥" + jsonObject.getString("biddingPrice"));
                myList.add(bidRecordEntity);
            }
        }
        list.clear();
        list.addAll(myList);
        if (detailsBisRecordAdapter == null) {
            detailsBisRecordAdapter = new DetailsBisRecordAdapter(getActivity(), list);
            recyclerView.setAdapter(detailsBisRecordAdapter);
        } else {
            detailsBisRecordAdapter.notifyDataSetChanged();
        }
    }

    //设置 竞拍商品
    @SuppressLint("SetTextI18n")
    private void setBidViewData(JSONObject object) {
        ll_lastTime.setVisibility(View.VISIBLE);
        v_line.setVisibility(View.VISIBLE);
        v_line.setBackgroundColor(Color.WHITE);
        if (isFirst) {
            //获取出价记录
            JSONArray array = object.getJSONArray("biddingRecodeList");
            if (array == null || array.size() == 0) {
                rl_bid1.setVisibility(View.GONE);
            } else {
                rl_bid1.setVisibility(View.VISIBLE);
                setRecordList(array);
            }
            //获取  图片 链接
            List<String> url_list = new ArrayList<>();//存放图片的
            String[] url = object.getString("carouselImage").split(",");
            Collections.addAll(url_list, url);
            initBanner(url_list);//初始化  banner信息
            tv_nowMoney.setText(object.getString("lastBiddingPrice"));
            tv_oldMoney.setText("￥" + object.getString("originalPrice"));
            tv_oldMoney.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
            tv_goodName.setText(object.getString("title"));
            tv_goodDetail.setText(object.getString("description"));
            tv_openBid.setText("￥" + object.getString("upsetPrice"));
            tv_openBidOne.setText(object.getString("biddingUnit") + "拍币/次");
            tv_addPrice.setText("￥" + object.getString("biddingPriceUnit"));
            tv_bidLast.setText(object.getString("biddingCountdown") + "s");
            if ("1".equals(object.getString("differenceToBuy"))) {
                tv_chajia.setText("是");
            } else {
                tv_chajia.setText("否");
            }
            tv_tuibi.setText(FormattedDataUtils.decimalToPercentage(object.getString("refundRatio")));
            SPUtils.put(App.getContext(), "status", object.getString("status"));
            if ("10".equals(object.getString("status"))) {
                long time = Long.parseLong(object.getString("publishCountdown"));
                simpleCountDownTimer = new SimpleCountDownTimer(time, tv_lastTime);
                simpleCountDownTimer.
                        setOnFinishListener(new SimpleCountDownTimer.OnFinishListener() {
                            @Override
                            public void onFinish() {
                                SPUtils.put(App.getContext(), "status", "20");
                            }
                        }).start();
            } else {
                SPUtils.put(App.getContext(), "status", object.getString("status"));
                long time = Long.parseLong(object.getString("lastBiddingCountdown"));
                simpleCountDownTimer = new SimpleCountDownTimer(time, tv_lastTime);
                simpleCountDownTimer.start();
            }

            ll_bid2.setVisibility(View.VISIBLE);
            final String detail = object.getString("details");
            SPUtils.put(App.getContext(), "detail_url", detail);
            isFirst = false;
            webView.loadUrl(detail);
        }
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        scrollView.setScrollViewListener(new MyScrollView.ScrollViewListener() {
            @Override
            public void onScrollChanged(MyScrollView scrollView, int x, int y, int oldx, int oldy) {
                setTitleBarStatus(y);
                currentY = y;
            }
        });
    }

    /**
     * 设置标题栏状态
     */
    private void setTitleBarStatus(int currentY) {
        if (currentY <= 0) {//顶部
            headerRel.getBackground().setAlpha(0);
            titleBar.setVisibility(View.GONE);
            iconBar.setVisibility(View.VISIBLE);
        } else if (currentY > 0 && currentY <= 500) {//滑动过程
            float scale = (float) currentY / 500;
            float alpha = (255 * scale);
            headerRel.getBackground().setAlpha((int) alpha);//设置背景色渐变
            titleBar.setVisibility(View.VISIBLE);
            iconBar.setVisibility(View.VISIBLE);
            //按钮标题的透明度
            backImg1.setImageAlpha(255 - (int) alpha);
            shareImg1.setImageAlpha(255 - (int) alpha);
            //文字标题的透明度
            backImg.setImageAlpha((int) alpha);
            shareImg.setImageAlpha((int) alpha);
            //设置字体颜色的变化
            slidingTabLayout.setTextSelectColor(getAlphaColorSelect(scale));
            slidingTabLayout.setTextUnselectColor(getAlphaColorUnSelect(scale));
            slidingTabLayout.setIndicatorColor(getAlphaIndicatorColorSelect(scale));
        } else {//滑动结束
            headerRel.getBackground().setAlpha(255);
            iconBar.setVisibility(View.GONE);
        }
    }

    //设置webView
    @SuppressLint({"SetJavaScriptEnabled", "ClickableViewAccessibility"})
    private void setWebView() {
        webView = view.findViewById(R.id.webView);
        final WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setAppCacheMaxSize(1024 * 1024 * 8);
        String appCachePath = App.getContext().getCacheDir().getAbsolutePath();
        settings.setAppCachePath(appCachePath);
        settings.setAllowFileAccess(true);
        settings.setAppCacheEnabled(true);
        //解除数据阻止
        settings.setBlockNetworkImage(false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE);
            settings.setMixedContentMode(2);
        }
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                //网页在webView中打开
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP) {//安卓5.0的加载方法
                    view.loadUrl(request.toString());
                } else {//5.0以上的加载方法
                    view.loadUrl(request.getUrl().toString());
                }
                return true;
            }

            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                Log.e("Tag", "onReceivedError: ");
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();  // 接受所有网站的证书
            }

            //
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
            }

            @Override
            public void onPageFinished(WebView view, String url) {
            }
        });

        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
            }
        });
    }

    private int getAlphaColorSelect(float f) {
        return Color.argb((int) (f * 255), 0x33, 0x33, 0x33);
    }

    private int getAlphaColorUnSelect(float f) {
        return Color.argb((int) (f * 255), 0x66, 0x66, 0x66);
    }

    private int getAlphaIndicatorColorSelect(float f) {
        return Color.argb((int) (f * 255), 0xFF, 0x66, 0x00);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
